//
//  SXHLocationHandler.m
//  ZLZKBaseUtils
//
//  Created by sxh on 2021/4/20.
//

#import "SXHLocationHandler.h"

#define WK(weakSelf) __weak __typeof(&*self)weakSelf = self;

@interface SXHLocationHandler()
<
    CLLocationManagerDelegate
>
///定位服务管理类
@property (nonatomic, strong) CLLocationManager *locationManager;
///初始化地理编码器
@property (nonatomic, strong) CLGeocoder *geocoder;

@property (nonatomic, strong) LocationBlock locationBlock;

@end

@implementation SXHLocationHandler

+ (instancetype)shared {
    static SXHLocationHandler *shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[SXHLocationHandler alloc] init];
    });
    return shared;
}

- (void)startLocation:(LocationBlock)result {
    _locationBlock = result;
    [self initLocationServicce];
}

/**
    初始化定位服务
 */
- (void)initLocationServicce {
   
    // 开始定位
    [self.locationManager startUpdatingLocation];
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    NSLog(@"%lu",(unsigned long)locations.count);
    CLLocation * location = locations.lastObject;
//    // 纬度
//    CLLocationDegrees latitude = location.coordinate.latitude;
//    // 经度
//    CLLocationDegrees longitude = location.coordinate.longitude;
//    NSLog(@"%@",[NSString stringWithFormat:@"%lf", location.coordinate.longitude]);
    NSLog(@"经度：%f,纬度：%f,海拔：%f,航向：%f,行走速度：%f", location.coordinate.longitude, location.coordinate.latitude,location.altitude,location.course,location.speed);

    WK(weakSelf)
    [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        [weakSelf.locationManager stopUpdatingLocation];
            if (placemarks.count > 0) {
                CLPlacemark *placemark = [placemarks objectAtIndex:0];
                NSLog(@"%@",placemark.name);
                //获取城市
                NSString *city = placemark.locality;
                if (!city) {
                    //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                    city = placemark.administrativeArea;
                }
                // 位置名
                NSLog(@"name,%@",placemark.name);
                // 街道
                NSLog(@"thoroughfare,%@",placemark.thoroughfare);
                // 子街道
                NSLog(@"subThoroughfare,%@",placemark.subThoroughfare);
                // 市
                NSLog(@"locality,%@",placemark.locality);
                // 区
                NSLog(@"subLocality,%@",placemark.subLocality);
                // 国家
                NSLog(@"country,%@",placemark.country);
                NSString *address = [NSString stringWithFormat:@"%@%@%@%@%@%@", placemark.country, placemark.administrativeArea, placemark.locality, placemark.subLocality, placemark.thoroughfare, placemark.name];
                weakSelf.locationBlock(location, address);
            }else if (error == nil && [placemarks count] == 0) {
                NSLog(@"No results were returned.");
                weakSelf.locationBlock(location, nil);
            } else if (error != nil){
                NSLog(@"An error occurred = %@", error);
                weakSelf.locationBlock(location, nil);
            }
            
        }];
}

#pragma mark - setter && getter
- (CLLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        [_locationManager requestAlwaysAuthorization];
        _locationManager.delegate = self;
        // 定位精度到米
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        // 过滤器为空
        _locationManager.distanceFilter = kCLDistanceFilterNone;
    }
    return _locationManager;
}

- (CLGeocoder *)geocoder {
    if (!_geocoder) {
        _geocoder = [[CLGeocoder alloc] init];
    }
    return _geocoder;
}

@end
